package com.grm.security.login;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 自定义密码比对逻辑，需要自定义盐值时可使用此类
 *
 * @author gaorimao
 * @date 2022/02/08
 */
@Slf4j
public class PasswordCheckHandler extends DaoAuthenticationProvider {

    @Value("${password.secret}")
    private String secret;

    public PasswordCheckHandler(UserDetailsService userDetailsService) {
        // 这个地方一定要对userDetailsService赋值，不然userDetailsService是null
        setUserDetailsService(userDetailsService);
        setPasswordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void additionalAuthenticationChecks(UserDetails userDetails,
                                                  UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        // authentication.getCredentials()得到的是密码
        if (authentication.getCredentials() != null) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String password = authentication.getCredentials().toString();
            String dbPassword = userDetails.getPassword();
            // encode(加密前,加密后)
            boolean isMatch = encoder.matches(password+secret,dbPassword);
            if (!isMatch) {
                throw new BadCredentialsException("BadCredentialsException：密码错误！");
            }
        }
    }
}

